import React, { useEffect, useRef, useState } from 'react';
import { Form, InputNumber, message, Modal, Select } from 'antd';
import { getStrategyList, repeatCallTask } from 'admin/servers/servers';
import { StrategyInfo, TaskStrategyInfo } from 'admin/schema/Strategy';
import { SelectValue } from 'antd/lib/select';
import { clearNull } from 'utils/tools';
import LastCallStrategy from './LastCallStrategy';

type IProps = {
  taskId: number;
  show: boolean;
  callBack: (data?: any) => void;
};

/**任务重呼 */
const CallRepeatPop: React.FC<IProps> = (props: IProps) => {
  const [form] = Form.useForm();
  const [strategyArr, setStrategyArr] = useState<StrategyInfo[]>([]);
  const strategyRef = useRef([]);
  const strategyVal = strategyRef.current as TaskStrategyInfo[];
  const { taskId, show, callBack } = props;

  useEffect(() => {
    console.log('####重呼弹窗====render');
    if (show) {
      initStrategyList();
    }
  }, [show]);

  function handleClose() {
    // 恢复默认
    strategyRef.current = [];
    form.resetFields();
    callBack();
  }

  function handleOK() {
    form.validateFields().then(async () => {
      // 表单验证通过
      const val = form.getFieldsValue();
      const strategyValue = strategyVal.filter((item: TaskStrategyInfo) => {
        return item.strategies?.length;
      });
      // 策略项-JSON字符串
      if (strategyValue.length) {
        val.strategyValue = JSON.stringify(strategyValue);
      }
      console.log(val, '重呼-入参');
      try {
        const res = await repeatCallTask(taskId, clearNull(val));
        if (res.code === 0) {
          message.success('重呼成功');
          callBack(true);
          handleClose();
        }
      } catch (error) {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      }
    });
  }

  function verifyNull(message: string) {
    return [{ required: true, message: message }];
  }

  /**
   * 获取策略项列表数据
   */
  function initStrategyList(strategyVal?: TaskStrategyInfo[]) {
    getStrategyList({
      pageSize: 10000,
      pageNo: 1,
    })
      .then(res => {
        const list = res.data;
        if (list && list.length) {
          setStrategyArr(list);
        }
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }
  /**策略项改版 */
  function onStrategyChange(val: SelectValue, strategyInfo: StrategyInfo, index: number): void {
    const valArr: { key?: string; value?: string }[] = [];
    (val as string[]).forEach(item => {
      const aim = strategyInfo.values?.find(child => child.value === item);
      aim && valArr.push(aim);
    });

    strategyVal[index] = {
      strategyId: strategyInfo.strategyOptionId,
      strategyName: strategyInfo.strategyOptionName,
      referColumn: strategyInfo.referColumn,
      strategies: valArr,
    };
    console.log(strategyVal, 'strategyVal-最新');
  }
  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 18 },
  };
  return (
    <Modal
      width={600}
      title="重呼策略设置"
      visible={show ? true : false}
      onOk={handleOK}
      onCancel={handleClose}
      destroyOnClose
    >
      <LastCallStrategy taskId={taskId} />
      <Form {...layout} form={form} layout="horizontal">
        {
          <>
            {strategyArr?.map((item, index) => {
              const option = item.values?.map(val => {
                return {
                  label: val.key as string,
                  value: val.value as string,
                };
              });
              return (
                <Form.Item label={item.referName} key={index}>
                  <Select
                    placeholder="请选择"
                    mode="multiple"
                    options={option}
                    maxTagPlaceholder=".."
                    maxTagCount={5}
                    // defaultValue={item.initialValue}
                    onChange={val => {
                      onStrategyChange(val, item, index);
                    }}
                  />
                </Form.Item>
              );
            })}
            <Form.Item
              label="外呼时间间隔"
              name="callTimeInterval"
              rules={verifyNull('请输入1-14400内的数字')}
            >
              <>
                <Form.Item name="callTimeInterval" noStyle>
                  <InputNumber
                    min={1}
                    max={14400}
                    precision={0}
                    style={{ width: 200 }}
                    placeholder="请输入1-14400内的数字"
                  />
                </Form.Item>
                <span style={{ marginLeft: 12 }}>分钟</span>
              </>
            </Form.Item>
          </>
        }
      </Form>
    </Modal>
  );
};

export default CallRepeatPop;
